import request from '@system.request'
import router from '@system.router'
import prompt from '@system.prompt'
import { sendMonitor } from './ajax'
import pkg from '@system.package'

export const installPkg = adData => {
  Promise.all(sendMonitor(adData.dn_inst_start))
  pkg.install({
    package: adData.package_name,
    success({ result }) {
      Promise.all(
        adData.dn_inst_succ.map(url => {
          return sendMonitor({ url, ua })
        })
      )
    },
    fail(e) {
      console.error(e)
    }
  })
}
export const checkDownloading = (adData, token, ua) => {
  return new Promise(resolve => {
    request.onDownloadComplete({
      token,
      success({ uri }) {
        // console.log(3)
        Promise.all(
          adData.dn_succ.map(url => {
            return sendMonitor({ url, ua })
          })
        )
        adData.isInstalled = false
        adData.rpk_uri = uri
        router.push({ uri })
        // installPkg(adData)
      },
      fail(e) {
        console.error(e)
      }
    })
  })
}

export default function(adData, ua) {
  if (adData.rpk_uri) {
    router.push({ uri: adData.rpk_uri })
    return Promise.reject()
  }
  if (adData.isInstalled) {
    prompt.showToast({
      message: '正在下载'
    })
    return Promise.reject()
  }
  Promise.all(
    adData.dn_start.map(url => {
      return sendMonitor({ url, ua })
    })
  )
  request.download({
    url: adData.dUrl[0],
    filname: adData.app_name,
    description: adData.app_name,
    success({ token }) {
      adData.isInstalled = true
      prompt.showToast({
        message: '正在下载'
      })
      checkDownloading(adData, token, ua)
    },
    fail(e) {
      console.error(e)
    }
  })
}
